package com.aiolos.wxdc.handler;

import com.aiolos.wxdc.enums.ResultEnum;
import com.aiolos.wxdc.exception.ResponseBankException;
import com.aiolos.wxdc.exception.SellException;
import com.aiolos.wxdc.exception.SellerAuthorizeException;
import com.aiolos.wxdc.utils.ResultVOUtils;
import com.aiolos.wxdc.vo.ResultVO;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import java.util.NoSuchElementException;

/**
 * 统一异常处理类
 */
@ControllerAdvice
public class AllExceptionHandler {

    /**
     * 拦截登录异常——SellerAuthorizeException
     * 跳转到list表页
     * @return
     */
    @ExceptionHandler(value = SellerAuthorizeException.class)
    public ModelAndView handlerAuthorizeException(){
        return new ModelAndView("redirect:/seller/product/list");
    }

    /**
     * 统一处理SellException异常，统一其json返回结果
     * @return
     */
    @ExceptionHandler(value = SellException.class)
    @ResponseBody
    public ResultVO handlerSellException(SellException e){
        return ResultVOUtils.error(e.getCode(),e.getMessage());
    }

    /**
     * 统一处理NoSuchElementException异常，统一其json返回结果
     * @return
     */
    @ExceptionHandler(value = NoSuchElementException.class)
    @ResponseBody
    public ResultVO handlerNoSuchElementException(NoSuchElementException e){
        return ResultVOUtils.error(ResultEnum.PRODUCT_NOT_EXIST.getCode(),ResultEnum.PRODUCT_NOT_EXIST.getMessage());
    }

    /**
     * 统一处理ResponseBankException异常,指定其Http Status code为403
     * @param e
     * @return
     */
    @ExceptionHandler(value = ResponseBankException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResultVO handlerResponseBankException(NoSuchElementException e){
        return ResultVOUtils.error(ResultEnum.PRODUCT_NOT_EXIST.getCode(),ResultEnum.PRODUCT_NOT_EXIST.getMessage());
    }
}
